<template>
  <div class="search-container">
    <div class="search-box">
      <input 
        type="text" 
        v-model="keyword"
        @input="handleInput"
        @focus="showSuggestions = true"
        @blur="handleBlur"
        placeholder="搜索电影、电视剧、综艺"
      >
      <i class="search-icon">🔍</i>
    </div>
    <div class="suggestions" v-show="showSuggestions && suggestions.length">
      <ul>
        <li 
          v-for="item in suggestions" 
          :key="item.id"
          @click="handleSelect(item)"
        >
          <span>{{ item.name }}</span>
          <span class="type">{{ item.type }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onCreated } from 'vue'
import { useRouter } from 'vue-router'
import { debounce } from 'lodash-es'
import { movieApi } from '@/api/movie'

const router = useRouter()
const keyword = ref('')
const suggestions = ref([])
const showSuggestions = ref(false)

const debouncedSearch = debounce(searchMovies, 300)

async function searchMovies() {
  if (!keyword.value.trim()) {
    suggestions.value = []
    return
  }
  try {
    const response = await movieApi.searchMovies(keyword.value)
    suggestions.value = response.data
  } catch (error) {
    console.error('搜索失败:', error)
  }
}

function handleInput() {
  debouncedSearch()
}

function handleSelect(item) {
  router.push(`/movie/${item.id}`)
  keyword.value = ''
  suggestions.value = []
}

function handleBlur() {
  setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}
</script>

<style scoped>
.search-container {
  position: relative;
  width: 300px;
}

.search-box {
  position: relative;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-top: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  z-index: 1000;
}

.suggestions li {
  padding: 8px 12px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
}

.suggestions li:hover {
  background: #f5f5f5;
}

.type {
  color: #999;
  font-size: 12px;
}
</style> 